package com.ht.WeNas.utils;

import java.net.URLConnection;
import java.nio.file.Path;
import java.util.Comparator;

public class MyPathUtil {
    public static String toPathString(Path path) {
        return path.toAbsolutePath().toString().replaceAll("\\\\", "/");
    }

    /**
     * 基于Path的ContentType分类文件</br>
     * 通过path字符串获取ContentType，然后和传入的ContentType进行前缀比较，比较成功返回true
     * @param path 文件Path
     * @param contentTypePrefix 保留的文件ContentType前缀
     * @return 对象是否保留
     */
    public static boolean contentTypeFilter(Path path, String contentTypePrefix) {
        try {
            // 用这种基于文件扩展名的方式来获取文件类型更快
            return URLConnection.guessContentTypeFromName(path.toString()).startsWith(contentTypePrefix);
        } catch (Exception e) {
            return false;
        }
    }

    public static Comparator<Path> getNaturalComparator() {
        return new Comparator<>() {
            @Override
            public int compare(Path o1, Path o2) {
                return splitAndCompare(o1.toString(), o2.toString());
            }

            private int splitAndCompare(String s1, String s2) {
                String[] splitS1 = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
                String[] splitS2 = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

                int len = Math.min(splitS1.length, splitS2.length);

                for (int i = 0; i < len; i++) {
                    String part1 = splitS1[i];
                    String part2 = splitS2[i];

                    if (isNumber(part1) && isNumber(part2)) {
                        // 处理超大数字比较
                        int numberCompare = compareNumberStrings(part1, part2);
                        if (numberCompare != 0) {
                            return numberCompare;
                        }
                    } else {
                        int strCompare = part1.compareTo(part2);
                        if (strCompare != 0) {
                            return strCompare;
                        }
                    }
                }

                return Integer.compare(splitS1.length, splitS2.length);
            }

            private boolean isNumber(String s) {
                return s.matches("\\d+");
            }

            private int compareNumberStrings(String numStr1, String numStr2) {
                // 先比较长度
                if (numStr1.length() != numStr2.length()) {
                    return Integer.compare(numStr1.length(), numStr2.length());
                }
                // 长度相同则逐位比较
                for (int i = 0; i < numStr1.length(); i++) {
                    char c1 = numStr1.charAt(i);
                    char c2 = numStr2.charAt(i);
                    if (c1 != c2) {
                        return Character.compare(c1, c2);
                    }
                }
                return 0;
            }
        };
    }
}
